package apps.edit;

import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

import screen.*;
import keyboard.*;

public class Edit extends JFrame {
    private static final Toolkit tk = Toolkit.getDefaultToolkit();
    private Screen scr = new Screen();
    private VRAM ram = scr.getVRAM();
    private Container c = getContentPane();
    private int line = 1;
    private boolean isAtLineFirst = true;
    private StringBuilder lineRecorder = new StringBuilder();
    private ArrayList<StringBuilder> lineRecorders = new ArrayList<>();
    private void initialize() {
        setSize(tk.getScreenSize());
        setAlwaysOnTop(true);
        setResizable(false);
        setUndecorated(true);
        setVisible(true);
        setDefaultCloseOperation(2);
    }
    public Edit() {
        initialize();
        c.setBackground(Color.BLACK);
        c.add(ram);
        scr.println("1 |_");
        addKeyListener(new EditKeyListener());
    }
    public static void planeMain(String[] args) {
        new Edit();
    }

    public static void main(String[] args) {
        planeMain(args); // compatible with traditional java
    }

    public class EditKeyListener extends KeyAdapter {
        private KeyRecorder recorder = new KeyRecorder(scr);

        @Override
        public void keyPressed(KeyEvent e) {
            int code = e.getKeyCode();
            char c = e.getKeyChar();
            if (c >= 32 && c <= 127) {
                recorder.add(c);
                lineRecorder.append(c);
            }
            if (code == KeyEvent.VK_ENTER) {
                line++;
                scr.discard();
                scr.println("");
                scr.print(line + " |_");
                lineRecorders.add(new StringBuilder(lineRecorder.toString()));
                lineRecorder = new StringBuilder();
            }
            if (code == KeyEvent.VK_BACK_SPACE) {
                recorder.add('\b');
                try {
                    lineRecorder.delete(lineRecorder.length() - 1, lineRecorder.length());
                } catch (Exception ex) {
                    isAtLineFirst = false;
                    line--;
                    scr.discardLine();
                    scr.print("_");
                    lineRecorder = new StringBuilder(lineRecorders.get(lineRecorders.size() - 1));
                    lineRecorders.remove(lineRecorders.size() - 1);
                }
            }
        }
    }
}